package com.company.project.interceptor;

import com.alibaba.fastjson.JSON;
import com.company.project.core.Result;
import com.company.project.core.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.company.project.utils.CommonUtils.getIpAddress;
import static com.company.project.utils.CommonUtils.responseResult;

/**
 * 认证拦截器
 *
 * @author chenx
 * @date 2016/4/23
 */
public class CertificationInterceptor extends BaseInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(CertificationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证签名
        boolean pass = validateSign(request);
        if (pass) {
            return true;
        } else {
            LOGGER.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}",
                    request.getRequestURI(), getIpAddress(request), JSON.toJSONString(request.getParameterMap()));
            Result result = new Result();
            result.setCode(ResultCode.UNAUTHORIZED).setMessage("签名认证失败");
            responseResult(response, result);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * 一个简单的签名认证，规则：
     * 1. 将请求参数按ascii码排序
     * 2. 拼接为a=value&b=value...这样的字符串（不包含sign）
     * 3. 混合密钥（secret）进行md5获得签名，与请求的签名进行比较
     */
//    private boolean validateSign(HttpServletRequest request) {
//        String requestSign = request.getParameter("sign");//获得请求签名，如sign=19e907700db7ad91318424a97c54ed57
//        if (StringUtils.isEmpty(requestSign)) {
//            return true;
//        }
//        List<String> keys = new ArrayList<String>(request.getParameterMap().keySet());
//        keys.remove("sign");//排除sign参数
//        Collections.sort(keys);//排序
//
//        StringBuilder sb = new StringBuilder();
//        for (String key : keys) {
//            sb.append(key).append("=").append(request.getParameter(key)).append("&");//拼接字符串
//        }
//        String linkString = sb.toString();
//        linkString = StringUtils.substring(linkString, 0, linkString.length() - 1);//去除最后一个'&'
//
//        String secret = "Potato";//密钥，自己修改
//        String sign = DigestUtils.md5Hex(linkString + secret);//混合密钥md5
//
//        return StringUtils.equals(sign, requestSign);//比较
//    }
        private boolean validateSign(HttpServletRequest request) {
         String token= request.getHeader("x-auth-token");
         HttpSession session=request.getSession();
         String sessionToken= (String) session.getAttribute("token");
         return StringUtils.equals(token, sessionToken);//比较
    }
}
